package com.leha.mp.api.websockets;

import com.leha.mp.core.services.PushServices;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;

@Log4j2
public class WSHandler extends TextWebSocketHandler {
    public void setPushServices(PushServices pushServices) {
        this.pushServices = pushServices;
    }

    private PushServices pushServices;


    public WSHandler() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String[] params = session.getUri().getQuery().split("=");
        if(params.length != 2) {
            TextMessage returnMessage = new TextMessage("参数错误");
            session.sendMessage(returnMessage);
            session.close();
        }
        if(params[0].equals("uid")) {
            pushServices.UserEnter(Integer.valueOf(params[1]), session);
        } else {
            pushServices.DoctorEnter(Integer.valueOf(params[1]), session);
        }
    }

    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        pushServices.userDisconnect(session.getId());
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }
}